package com.example.server.service;

import com.example.server.domain.Students;
import com.example.server.mapper.StudentsMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.UUID;

//所有的业务逻辑方法都放在这个类里
//CRUD--create, read, update, delete
@Service
public class StudentsService {

    private final StudentsMapper studentsMapper;

    public StudentsService(StudentsMapper studentsMapper) {
        this.studentsMapper = studentsMapper;
    }

    public Students getStudentById(Long id) {
        return studentsMapper.selectByPrimaryKey(id);
    }
    public List<Students> getAllStudents() {
        return studentsMapper.selectAll();
    }
    public void createStudent(Students students) {
        studentsMapper.insert(students);
    }
    public void updateStudent(Students students) {
        studentsMapper.updateByPrimaryKey(students);
    }
    public void deleteStudent(Long id) {
        studentsMapper.deleteByPrimaryKey(id);
    }

    public String uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", ""); //生成uuid
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileName = uuid + "." + fileSuffix;
        //TODO 保存文件到服务器
        String path = "D:\\woniu\\shixun\\qingdaokeji\\dorm\\backend\\server\\target\\classes\\static\\img\\" + fileName;
        try {
            file.transferTo(new java.io.File(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public List<Students> querylike(String sname) {
        //sql= select * from students where sname like '%sname%'

        return studentsMapper.querylike(sname);

    }
}
